package br.com.rodrigo.activemq;

import java.net.MalformedURLException;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import br.com.rodrigo.constants.Constants;

/**
 *
 * <b>Descricao da Classe:</b><br>
 * TODO Explicar detalhadamente proposito da classe
 *
 * @author rodrigo.bacellar
 * @since 17/11/2014
 *
 */
public class Receiver implements MessageListener
{
    private final Logger logger = LoggerFactory.getLogger(Receiver.class);

    @Value(Constants.EMAIL_FROM)
    private String user;

    @Value(Constants.EMAIL_PASSWORD)
    private String password;

    @Value(Constants.EMAIL_TO)
    private String to;

    @Value(Constants.EMAIL_SUBJECT)
    private String subject;

    @Value(Constants.EMAIL_HOSTNAME)
    private String hostname;

    public void onMessage(Message msg)
    {

        TextMessage txt = (TextMessage) msg;

        try
        {
            logger.info("Mensagem recebida.MSG[{}]", txt.getText());

            sendEmail(txt.getText());
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (EmailException e)
        {
            e.printStackTrace();
        }
        catch (JMSException e)
        {
            e.printStackTrace();
        }
    }

    private void sendEmail(String text) throws EmailException, MalformedURLException
    {

        HtmlEmail htmlEmail = new HtmlEmail();

        /** AUTENTICACAO */
        htmlEmail.setHostName("smtp.gmail.com");
        htmlEmail.setAuthentication("rodrigo.haus@gmail.com", "061rd0r#@h561");
        htmlEmail.setSmtpPort(465);
        htmlEmail.setSSL(true);

        /** FROM */
        htmlEmail.setFrom("rodrigo.haus@gmail.com", "Rodrigo");

        /** TO */
        htmlEmail.addTo("rodrigo.haus@gmail.com", "Rodrigo");

        /** ASSUNTO */
        htmlEmail.setSubject("Teste");

        /** BODY */
        StringBuffer sb = new StringBuffer();
        sb.append("<html> Teste de envio de email com o ActiveMQ:<br/><br/>");
        sb.append(text);
        sb.append("</html>");

        htmlEmail.setHtmlMsg(sb.toString());

        htmlEmail.setDebug(false);
        htmlEmail.send();

        logger.info("Mensagem enviada por email.");

    }

}
